﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace SpeedTest
{
	public enum EditMode
	{
		CreateMode,
		EditMode
	}

	public partial class PanelPlan : UserControl
	{
		private Data data = null;
		private string itemID = String.Empty;
		private DataTable planTable = null;
		private EditMode mode = EditMode.EditMode;

		public PanelPlan(Data data, EditMode mode)
		{
			InitializeComponent();
			this.mode = mode;
			this.data = data;
			EnableInput(true);

		}

		public PanelPlan(Data data, string itemID, bool enableInput)
		{
			InitializeComponent();
			this.data = data;
			this.itemID = itemID;
			LoadData();
			EnableInput(false);
			InitializeStats();
		}

        public delegate void OnSave(string id, NodeType nodeType);
		public event OnSave Save;
		public delegate void OnCancel();
		public event OnCancel Cancel;

		private bool LoadData()
		{
			if (data != null)
			{
				planTable = data.GetPlanByID(itemID);
			}
			else { return false; }

			if (planTable != null)
			{
				txtTitle.Text = planTable.Rows[0]["Description"].ToString();
				txtReferenceNum.Text = planTable.Rows[0]["ReferenceNumber"].ToString();
			}
			else { return false; }

			return true;
		}

		private void btnEdit_Click(object sender, EventArgs e)
		{
			EnableInput(true);
		}

		private void btnSave_Click(object sender, EventArgs e)
		{
            if (!ValidateInput()) { return; }

			if (mode == EditMode.EditMode)
			{
				planTable.Rows[0]["Description"] = txtTitle.Text;
				planTable.Rows[0]["ReferenceNumber"] = txtReferenceNum.Text;

				data.UpdatePlanByID(planTable, itemID);
			}
			else
			{
				planTable = new DataTable();
				planTable.Columns.Add("Description");
				planTable.Columns.Add("ReferenceNumber");
				planTable.Columns.Add("CreatorID") ;
				planTable.Columns.Add("ReleaseID");

				string[] record = new string[4];
				record[0] = txtTitle.Text;
				record[1] = txtReferenceNum.Text;
				record[2] = data.User.UserID;
				record[3] = Properties.Settings.Default.ActiveReleaseID;

				planTable.Rows.Add(record);

				itemID = data.InsertPlan(planTable).ToString();
			}

			EnableInput(false);
			Save.Invoke(itemID, NodeType.PlanNode);
		}

        private bool ValidateInput()
        {
            string requiredFields = String.Empty;

            if (String.IsNullOrEmpty(txtTitle.Text)) { requiredFields += "Title\n"; }

            if (!String.IsNullOrEmpty(requiredFields))
            {
                MessageBox.Show("The following required fields are empty\n" + requiredFields, "Error");
                return false;
            }

            return true;
        }

		private void btnCancel_Click(object sender, EventArgs e)
		{
			if (mode == EditMode.EditMode)
			{
				LoadData();
				EnableInput(false);
			}
			else
			{
				Cancel.Invoke();
			}
		}

		private void EnableInput(bool enable)
		{
			txtReferenceNum.Enabled = enable;
			txtTitle.Enabled = enable;

			groupStats.Enabled = !enable;	//disabled when editing, not when viewing.
			if (IsPermitted(btnEdit, data.User.Plans)) { btnEdit.Enabled = !enable; }
			else { btnEdit.Enabled = false; }

			btnSave.Enabled = enable;
			btnCancel.Enabled = enable;
		}

		private bool IsPermitted(Button btn, Permissions perm)
		{
			if (btn == btnEdit) { return perm.Edit; }

			return false;
		}

		private void txtReferenceNum_KeyPress(object sender, KeyPressEventArgs e)
		{
			int parsedNumber = 0;
			e.Handled = !Int32.TryParse(e.KeyChar.ToString(), out parsedNumber);
		}

		private void InitializeStats()
		{
			//Get the list of environments and set the first as selected
			cmboEnvirons.ValueMember = "Value";
			cmboEnvirons.DisplayMember = "Text";

			DataTable envTable = data.GetEnvironments();
			if (envTable != null && envTable.Rows.Count > 0)
			{
				FillCombo(envTable, envTable.Columns["ID"].Ordinal, envTable.Columns["Description"].Ordinal, cmboEnvirons);
				if (cmboEnvirons.Items.Count > 0) { cmboEnvirons.SelectedIndex = 0; }
			}

		}

		private void cmboEnvirons_SelectedIndexChanged(object sender, EventArgs e)
		{
			ComboItem ci = (ComboItem)cmboEnvirons.SelectedItem;
			if (ci != null)
			{
				//reset labels
				lblTotalCases.Text = "0";
				lblNotRun.Text = "0";
				lblFailed.Text = "0";
				lblPassed.Text = "0";
				lblBlocked.Text = "0";
				lblRescheduled.Text = "0";
				lblUntestable.Text = "0";

				LoadStats(ci.Value);
			}
		}

		private void LoadStats(string environID)
		{
			if (data != null)
			{
				//Get total cases for first environ
				long totalCases = data.GetTotalCases(itemID, environID);
				lblTotalCases.Text = totalCases.ToString();

				//Get other run stats NOT RUN, FAILED, PASSED, BLOCKED, RESCHEDULED, UNTESTABLE
				DataTable statsTable = data.GetRunResultsSummary(itemID, environID);
				if (statsTable != null && statsTable.Rows.Count > 0)
				{
					for(int i = 0; i < statsTable.Rows.Count; i++)
					{
						switch (statsTable.Rows[i]["Result"].ToString())
						{
							case "NOT RUN":
								lblNotRun.Text = statsTable.Rows[i]["Total"].ToString();
								break;
							case "FAILED":
								lblFailed.Text = statsTable.Rows[i]["Total"].ToString();
								break;
							case "PASSED":
								lblPassed.Text = statsTable.Rows[i]["Total"].ToString();
								break;
							case "BLOCKED":
								lblBlocked.Text = statsTable.Rows[i]["Total"].ToString();
								break;
							case "RESCHEDULED":
								lblRescheduled.Text = statsTable.Rows[i]["Total"].ToString();
								break;
							case "UNTESTABLE":
								lblUntestable.Text = statsTable.Rows[i]["Total"].ToString();
								break;
						}
					}
				}
			}
		}

		private void FillCombo(DataTable table, int valueIndex, int textIndex, ComboBox combo)
		{
			if (table != null && table.Rows.Count > 0)
			{
				combo.Items.Clear();

				for (int i = 0; i < table.Rows.Count; i++)
				{
					ComboItem ci = new ComboItem();
					ci.Text = table.Rows[i][textIndex].ToString();
					ci.Value = table.Rows[i][valueIndex].ToString();

					combo.Items.Add(ci);
				}
			}
		}

	}
}
